local System = require"ecs/system/system"

local camera_control_system = class("CameraControlSystem",System){
    system_config = {
        type = SYSYTEM_TYPE_PROCESS;
        is_default_add = false;
        filter = {tiny.rejectAll()};
    },

    cam_mov_ox = 0;
    cam_mov_oy = 0;
    cam_mov_x = 0;
    cam_mov_y = 0;
}

function camera_control_system:_init()
    self.camera = box_core.get_shared("Camera")
    box_core.callback:register("wheelmoved",self,"wheelmoved")
    box_core.callback:register("mousemoved",self,"mousemoved")
    box_core.callback:register("mousepressed",self,"mousepressed")
    box_core.callback:register("mousereleased",self,"mousereleased")
end

function camera_control_system:postProcess(dt)
    local speed = 250
    local vx,vy = 0,0
    if love.keyboard.isDown("up") then
        vy = -speed
    end
    if love.keyboard.isDown("down") then
        vy = speed
    end
    if love.keyboard.isDown("left") then
        vx = -speed
    end
    if love.keyboard.isDown("right") then
        vx = speed
    end

    self.camera.x = self.camera.x + vx * dt
    self.camera.y = self.camera.y + vy * dt

    if love.mouse.isDown(3) then
        local mx,my = love.mouse.getPosition()
        local ofx,ofy = mx - self.cam_mov_ox,my - self.cam_mov_oy
        self.camera.x = self.cam_mov_x + -ofx * self.camera.scale
        self.camera.y = self.cam_mov_y + -ofy * self.camera.scale
    end
end

function camera_control_system:wheelmoved(x,y)
    local dt = love.timer.getDelta()
    if y > 0 then
        self.camera.scale = self.camera.scale + 50 * dt
    elseif y < 0 then
        self.camera.scale = self.camera.scale - 50 * dt
    end
end

function camera_control_system:mousemoved(mx,my,dx,dy,i)
    if love.mouse.isDown(2) then
        local dt = love.timer.getDelta()
        if dy > 0 then
            self.camera.rotation = self.camera.rotation + 5 * dt
        else
            self.camera.rotation = self.camera.rotation - 5 * dt
        end
    end
end

function camera_control_system:mousepressed(x,y,b)
    if b == 3 then
        self.cam_mov_ox,self.cam_mov_oy = x,y
        self.cam_mov_x,self.cam_mov_y = self.camera.x,self.camera.y
    end
end

function camera_control_system:mousereleased(x,y,b)
    -- if b == 3 then
    --     self.cam_mov_ox,self.cam_mov_oy = 0,0
    --     self.cam_mov_x,self.cam_mov_y = self.camera.x,self.camera.y
    -- end
end

return camera_control_system()